import time

from django.db import models


# Create your models here.

def upload_to_str(obj, file_name):
    name, suffix = file_name.split('.')[-2:]
    file_name = '{}{}.{}'.format(name, int(time.time() * 100), suffix)
    return 'storage/{}/{}'.format(time.strftime("%Y/%m-%d"), file_name)


class ImageStorage(models.Model):
    name = models.CharField('文件名称', max_length=200)
    suffix = models.CharField('文件后缀', max_length=10)
    save_model = models.IntegerField('保存类型', choices=((1, '本地保存'), (2, '阿里云')))
    file_obj = models.FileField(upload_to=upload_to_str, null=False, )
    file_key = models.CharField('云保存KEY', max_length=50, null=False, blank=False)
    width = models.FloatField('图片宽度', null=False, blank=False)
    height = models.FloatField('图片高度', null=False, blank=False)
    aspect_ratio = models.FloatField('宽高比', null=False, blank=False)
    size = models.FloatField('图片大小', null=False, blank=False)

    create_time = models.DateTimeField('创建时间', auto_now_add=True)
    is_delete = models.BooleanField('是否删除', default=False)

    def get_url(self):
        return self.file_obj.url if self.save_model == 1 else self.file_key
